package wili.sql;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * @author weila 2022年7月23日
 */
public class SqlResult {
	ResultSetMetaData meta;

	final int colNum;

	final List<MapData> rows = new ArrayList<>();

	final List<String> cnames;

	public SqlResult(ResultSet rs) throws SQLException {
		meta = rs.getMetaData();
		colNum = meta.getColumnCount();
		Map<String, Object> map = new HashMap<>();
		cnames = new ArrayList<>(colNum);
		while (rs.next()) {
			for (int i = 0; i < colNum; i++) {
				String cname = meta.getColumnName(i);
				Object col = rs.getObject(i);
				if (col instanceof java.sql.Clob) {
					map.put(cname, "Clob...");
				} else {
					map.put(cname, col);
				}
			}
			rows.add(new MapData(map));
		}
	}

	void log(Object msg) {
	}

	public void print() {
		List<Map<String, Object>> mList = MapData.mapListOf(rows);
		int[] wids = Coms.columnWidths_of_mapList(mList, cnames);
		for (int i = 0; i < rows.size(); i++) {
			MapData row = rows.get(i);
			String line = Coms.strOfMapValues(-1, row.map, cnames, wids);
			log(i + ": " + line);
		}
	}
}
